package controllers

import (
	"stacks/models"
	"stacks/services"
	"stacks/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

// PermissionController 权限控制器
type PermissionController struct {
	permissionService *services.PermissionService
}

// NewPermissionController 创建权限控制器实例
func NewPermissionController() *PermissionController {
	return &PermissionController{
		permissionService: services.NewPermissionService(),
	}
}

// GetPermissionList 获取权限列表
func (c *PermissionController) GetPermissionList(ctx *gin.Context) {
	tenantID, _ := strconv.ParseUint(ctx.Query("tenantId"), 10, 32)
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))

	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	permissions, total, err := c.permissionService.GetPermissionList(uint(tenantID), page, pageSize)
	if err != nil {
		utils.InternalError(ctx, "获取权限列表失败")
		return
	}

	utils.Success(ctx, gin.H{
		"list":  permissions,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// GetPermissionByID 根据ID获取权限
func (c *PermissionController) GetPermissionByID(ctx *gin.Context) {
	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 32)
	tenantID, _ := strconv.ParseUint(ctx.Query("tenantId"), 10, 32)

	permission, err := c.permissionService.GetPermissionByID(uint(id), uint(tenantID))
	if err != nil {
		utils.NotFound(ctx, "权限不存在")
		return
	}

	utils.Success(ctx, permission)
}

// CreatePermission 创建权限
func (c *PermissionController) CreatePermission(ctx *gin.Context) {
	var permission models.SysPermission
	if err := ctx.ShouldBindJSON(&permission); err != nil {
		utils.BadRequest(ctx, "请求参数错误")
		return
	}

	err := c.permissionService.CreatePermission(&permission)
	if err != nil {
		utils.BadRequest(ctx, err.Error())
		return
	}

	utils.Success(ctx, "创建成功")
}

// UpdatePermission 更新权限
func (c *PermissionController) UpdatePermission(ctx *gin.Context) {
	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 32)
	tenantID, _ := strconv.ParseUint(ctx.Query("tenantId"), 10, 32)

	var updates map[string]interface{}
	if err := ctx.ShouldBindJSON(&updates); err != nil {
		utils.BadRequest(ctx, "请求参数错误")
		return
	}

	err := c.permissionService.UpdatePermission(uint(id), uint(tenantID), updates)
	if err != nil {
		utils.BadRequest(ctx, err.Error())
		return
	}

	utils.Success(ctx, "更新成功")
}

// DeletePermission 删除权限
func (c *PermissionController) DeletePermission(ctx *gin.Context) {
	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 32)
	tenantID, _ := strconv.ParseUint(ctx.Query("tenantId"), 10, 32)

	err := c.permissionService.DeletePermission(uint(id), uint(tenantID))
	if err != nil {
		utils.BadRequest(ctx, err.Error())
		return
	}

	utils.Success(ctx, "删除成功")
}
